﻿using AzukiMap.Map;
using AzukiMap.MapSource;
using AzukiMap.Renderer;
using AzukiMap.Request;
using Geotools.Geometries;
using System.Xml.Linq;

namespace AzukiMap.Layer
{
    public class PostGisRasterIndexLayer : VectorLayer
    {
        PostGisSource _pgTable;
        //PostGisVectorRequest _pgRequest;
        PostGisRasterIndexRequest _pgRequest;
        PostGisRasterIndexParser _pgParser;
        RasterRenderer _renderer;

        public PostGisRasterIndexLayer(PostGisSource pgTable, MapCanvas mapCanvas, string name, GTPolygon extent, string indexColumn)
            : base((VectorSource)pgTable, mapCanvas, name, extent)
        {
            init(pgTable, indexColumn);
        }

        public PostGisRasterIndexLayer(PostGisSource pgTable, MapCanvas mapCanvas, string name, string indexColumn)
            : base((VectorSource)pgTable, mapCanvas, name)
        {
            init(pgTable, indexColumn);
        }

        void init(PostGisSource pgTable, string indexColumn)
        {
            _pgTable = pgTable;
            if (pgTable.GetColumnDataUri != null)
            {
                _pgRequest = new PostGisRasterIndexRequest(MapCanvas, this, pgTable.GetColumnDataUri, indexColumn);
            }
            else
            {
                _pgRequest = new PostGisRasterIndexRequest(MapCanvas, this, indexColumn);
            }
            _pgRequest.GetDataCompleted += new GetDataCompletedHandler(_pgRequest_GetDataCompleted);
        }

        public override void Draw()
        {
            if (_isRendering)
            {
                return;
            }
            if (!_isVisible)
            {
                return;
            }
            if (!CheckScale())
            {
                return;
            }
            _isRendering = true;
            _pgRequest.Request();
        }

        void _pgRequest_GetDataCompleted(object sender, GetDataCompletedArgs e)
        {
            //_pgParser = new PostGisVectorParser(e.DataStream);
            _pgParser = new PostGisRasterIndexParser(e.DataStream);
            int numOfGeom = _pgParser.NumOfObjects;

            // TODO: get uniq ID from records.
            int id = 0;
            IVectorStyle vStyle;
            //foreach (PostGisRecord record in _pgParser)
            foreach (RasterIndexRecord record in _pgParser)
            {
                _renderer.DrawRaster(id, record.Extent, record.RasterIndex);
            }
            _isRendering = false;
        }

        public override XElement ToXml()
        {
            return ToXml("PostGisLayer");
        }

        public override XElement ToXml(string elementName)
        {
            XElement vectorLayerXml = base.ToXml(elementName);
            return vectorLayerXml;
        }
    }
}
